package org.bdware.repository.webService.service;

import org.bdware.repository.webService.config.FileStorageProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Objects;

@Service
public class FileStorageServiceImpl implements FileStorageService{
    private final Path fileStorageLoc;
    Logger logger = LoggerFactory.getLogger(FileStorageServiceImpl.class);

    @Autowired
    public FileStorageServiceImpl(FileStorageProperties fileStorageProperties){
        this.fileStorageLoc = Paths.get(fileStorageProperties.getUploadDir()).toAbsolutePath().normalize();
        try {
            Files.createDirectories(this.fileStorageLoc);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String storeFile(MultipartFile file) {
        String fileName = StringUtils.cleanPath(Objects.requireNonNull(file.getOriginalFilename()));
        fileName = System.currentTimeMillis() + "_" + fileName;
        try {
            if (fileName.contains("..")) {
                logger.error("File name contains invalid path sequence");
            }
            Path targetLocation = this.fileStorageLoc.resolve(fileName);
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
            return fileName;
        } catch (IOException ex) {
            logger.error("Could not store file " + fileName + ". Please try again later!", ex);
        }
        return null;
    }

    @Override
    public Resource loadFileAsResource(String fileName) {
        try{
            Path filePath = this.fileStorageLoc.resolve(fileName).normalize();
            Resource resource = new UrlResource(filePath.toUri());
            if (resource.exists()){
                return resource;
            }else{
                logger.error("File not found" + fileName);
            }
        }catch (MalformedURLException ex){
            logger.error("File not found" + fileName);
        }
        return null;
    }
}
